package com.gable.exhibition.controller;

import com.alibaba.fastjson.JSON;
import com.gable.common.util.CacheData;
import com.gable.common.util.ImportExcel;
import com.gable.common.util.ReturnResultUtil;
import com.gable.common.util.StringUtil;
import com.gable.exhibition.model.User;
import com.gable.exhibition.service.HospitalService;
import com.gable.exhibition.util.CheckImportExcelHospital;
import com.gable.exhibition.util.MessageUtil;
import com.gable.exhibition.view.ImportExcelHospitalModel;
import com.gable.exhibition.view.HospitalView;
import com.gable.exhibition.view.ImportExcelView;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Lesson on 2018/1/4.
 */
@Controller
@RequestMapping(value="/hospital")
public class HospitalController {

    Logger logger = Logger.getLogger(this.getClass());

    @Autowired
    HospitalService hospitalService;


    @Autowired
    CheckImportExcelHospital checkImportExcelHospital;

    @RequestMapping(value = "/page")
    public String page(HttpServletRequest request, HttpServletResponse response){

        return "hospital/hospital-page";
    }

    @RequestMapping(value="/queryHospitalList",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryHospitalList(HttpServletRequest request, HttpServletResponse response, HospitalView hospitalView){
        try{
            ReturnResultUtil rru = hospitalService.queryHospitalList(hospitalView);
            logger.info(JSON.toJSONString(rru));
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500, MessageUtil.QUERYEXCEPTION);
    }

    @RequestMapping(value="/addOrUpdateHospital",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil addOrUpdateHospital(HttpServletRequest request, HttpServletResponse response, HospitalView hospitalView){
        try{
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            User user = CacheData.getSessionUser(null,1);
            if(hospitalView.getHospitalId() == null){
                hospitalView.setCreatePerson(user.getUserId());
                hospitalView.setCreateTime(df.format(new Date()));
            }else{
                hospitalView.setUpdatePerson(user.getUserId());
                hospitalView.setUpdateTime(df.format(new Date()));
            }

            return hospitalService.addOrUpdateHospital(hospitalView);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value="/queryHospitalInfo",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil queryHospitalInfo(HttpServletRequest request, HttpServletResponse response){
        try {
            if (StringUtil.isEmpty(request.getParameter("hospitalId"))) {
                return new ReturnResultUtil(500, MessageUtil.HSOPITALIDDOESTNOEXIST);
            }

            Long hospitalId = Long.parseLong(request.getParameter("hospitalId"));
            return hospitalService.queryHospitalInfo(hospitalId);
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    @RequestMapping(value= "/import")
    public String hospitalImport(HttpServletRequest request, HttpServletResponse response){
        return "hospital/hospital-import";
    }

    @RequestMapping(value="/hospitalExcel",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil hospitalExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("files");
        String rootPath = request.getSession().getServletContext().getRealPath(File.separator);
        try {
            Long ym = new Date().getTime();
            String filePath = "upload/" + ym;
            if (files != null && files.size() > 0) {
                for (MultipartFile m : files) {
                    if (m.getBytes().length == 0) {
                        return new ReturnResultUtil(500, MessageUtil.PLEASEUPLOADFILE);
                    }
                    String suffix = m.getOriginalFilename().substring(m.getOriginalFilename().lastIndexOf(".") + 1);
                    if (!suffix.equals("xlsx")) {
                        return new ReturnResultUtil(500, MessageUtil.FILEFORMATWRONG);
                    }
                    filePath = filePath + suffix;
                    File file = new File(rootPath + filePath);
                    if (file.exists()) {
                        file.delete();
                        file.mkdirs();
                    } else {
                        file.mkdirs();
                    }
                    m.transferTo(file);
                }
                User user = CacheData.getSessionUser(null,1);
                List<Object> list = ImportExcel.excelRead(rootPath + filePath, CheckImportExcelHospital.properties, ImportExcelHospitalModel.class);
                CheckImportExcelHospital.resultMap.put(user.getUserId(), list);
                logger.info("==================" + JSON.toJSONString(list));
                return new ReturnResultUtil(200, MessageUtil.UPLOADSUCCESS, list);

            } else {
                return new ReturnResultUtil(500, MessageUtil.UPLOADFILESERROR);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return  new ReturnResultUtil(500,MessageUtil.UPLOADEXCEPTION);
    }

    @RequestMapping(value="/checkExcelHospital",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil checkExcelHospital(HttpServletRequest request, HttpServletResponse response){
        ImportExcelView importExcelView = new ImportExcelView();
        try {
            User user = CacheData.getSessionUser(null,1);
            List<ImportExcelHospitalModel> list =(List<ImportExcelHospitalModel>)CheckImportExcelHospital.resultMap.get(user.getUserId());
            importExcelView = checkImportExcelHospital.checkHospital(list);
            return new ReturnResultUtil(200,MessageUtil.EXAMINESUCCESS,importExcelView);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.EXAMINEERROR);
    }

    @RequestMapping(value="/saveHospitalByExecl",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public ReturnResultUtil saveHospitalByExecl(HttpServletRequest request, HttpServletResponse response){
        try {
            User user = CacheData.getSessionUser(null, 1);
            List<ImportExcelHospitalModel> list = (List<ImportExcelHospitalModel>) CheckImportExcelHospital.resultMap.get(user.getUserId());
            ReturnResultUtil rru = hospitalService.saveHospitalByExcel(list,user);
            CheckImportExcelHospital.resultMap.remove(user.getUserId());
            return rru;
        }catch (Exception e){
            e.printStackTrace();
        }
        return new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION);
    }

    /**
     * 根据经纬度获取方圆两公里内医院
     * @param request
     * @param response
     * @param hospitalView
     * @return
     */
    @RequestMapping(value="/findNeighPosition",method = RequestMethod.POST, produces="application/json;charset=utf-8")
    @ResponseBody
    public String findNeighPosition(HttpServletRequest request, HttpServletResponse response,HospitalView hospitalView){
        try {
            ReturnResultUtil rru = hospitalService.queryHospitalListBySelect(hospitalView);
            logger.info(JSON.toJSONString(rru));
            return JSON.toJSONString(rru);
        }catch (Exception e){
            e.printStackTrace();
        }
        return JSON.toJSONString(new ReturnResultUtil(500,MessageUtil.SAVEEXCEPTION));
    }
}
